import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../widgets/platform/adaptive_card.dart';
import '../../../widgets/platform/adaptive_button.dart';
import '../../../widgets/platform/adaptive_text_field.dart';
import '../../../../core/platform/platform_detector.dart';

/// 组织管理页面
class OrgManagementPage extends ConsumerStatefulWidget {
  const OrgManagementPage({super.key});

  @override
  ConsumerState<OrgManagementPage> createState() => _OrgManagementPageState();
}

class _OrgManagementPageState extends ConsumerState<OrgManagementPage> {
  final _searchController = TextEditingController();
  final _formKey = GlobalKey<FormState>();
  String? _selectedOrgType;
  String? _selectedParentOrg;
  String? _selectedStatus;

  @override
  void initState() {
    super.initState();
    // 初始化时加载组织数据
    _loadOrgs();
  }

  @override
  void dispose() {
    _searchController.dispose();
    super.dispose();
  }

  void _loadOrgs() {
    // TODO: 实现加载组织数据的逻辑
  }

  void _searchOrgs(String query) {
    // TODO: 实现搜索组织逻辑
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        // 搜索和操作栏
        _buildSearchBar(),
        const SizedBox(height: 16),

        // 组织树形结构
        Expanded(
          child: _buildOrgTree(),
        ),
      ],
    );
  }

  Widget _buildSearchBar() {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 16.0),
      child: Row(
        children: [
          Expanded(
            child: AdaptiveTextField(
              controller: _searchController,
              labelText: '搜索组织',
              prefixIcon: Icons.search,
              hintText: '按组织名称搜索',
              onChanged: _searchOrgs,
            ),
          ),
          const SizedBox(width: 16),
          AdaptiveButton(
            onPressed: _showCreateOrgDialog,
            child: const SelectableText('创建组织'),
          ),
        ],
      ),
    );
  }

  Widget _buildOrgTree() {
    // 模拟组织数据
    final orgs = [
      {
        'id': 1,
        'name': '技术部',
        'code': 'TECH',
        'parentId': null,
        'children': [
          {
            'id': 6,
            'name': '前端组',
            'code': 'TECH_FE',
            'parentId': 1,
            'children': [],
          },
          {
            'id': 7,
            'name': '后端组',
            'code': 'TECH_BE',
            'parentId': 1,
            'children': [],
          },
          {
            'id': 8,
            'name': '移动端组',
            'code': 'TECH_MOBILE',
            'parentId': 1,
            'children': [],
          },
        ],
      },
      {
        'id': 2,
        'name': '产品部',
        'code': 'PRODUCT',
        'parentId': null,
        'children': [
          {
            'id': 9,
            'name': '产品规划组',
            'code': 'PRODUCT_PLAN',
            'parentId': 2,
            'children': [],
          },
          {
            'id': 10,
            'name': '用户研究组',
            'code': 'PRODUCT_UX',
            'parentId': 2,
            'children': [],
          },
        ],
      },
      {
        'id': 3,
        'name': '测试部',
        'code': 'QA',
        'parentId': null,
        'children': [
          {
            'id': 11,
            'name': '功能测试组',
            'code': 'QA_FUNC',
            'parentId': 3,
            'children': [],
          },
          {
            'id': 12,
            'name': '自动化测试组',
            'code': 'QA_AUTO',
            'parentId': 3,
            'children': [],
          },
        ],
      },
      {
        'id': 4,
        'name': '运维部',
        'code': 'OPS',
        'parentId': null,
        'children': [],
      },
      {
        'id': 5,
        'name': '设计部',
        'code': 'DESIGN',
        'parentId': null,
        'children': [],
      },
    ];

    return LayoutBuilder(
      builder: (context, constraints) {
        // 桌面平台使用树形结构
        if (PlatformDetector.isDesktop() || PlatformDetector.isWeb()) {
          return _buildDesktopTree(orgs);
        } else {
          // 移动平台使用列表结构
          return _buildMobileList(orgs);
        }
      },
    );
  }

  Widget _buildDesktopTree(List<Map<String, dynamic>> orgs) {
    return SingleChildScrollView(
      child: Column(
        children: orgs.map((org) => _buildOrgTreeNode(org, 0)).toList(),
      ),
    );
  }

  Widget _buildOrgTreeNode(Map<String, dynamic> org, int level) {
    final children = List<Map<String, dynamic>>.from(org['children'] ?? []);

    return Column(
      children: [
        AdaptiveCard(
          child: Row(
            children: [
              SizedBox(width: level * 24.0),
              if (children.isNotEmpty)
                const Icon(Icons.arrow_drop_down, size: 24)
              else
                const SizedBox(width: 24),
              const Icon(Icons.account_balance, color: Colors.blue),
              const SizedBox(width: 12),
              Expanded(
                child: SelectableText(
                  org['name'],
                  style: Theme.of(context).textTheme.titleMedium,
                ),
              ),
              SelectableText(
                org['code'],
                style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                      color: Colors.grey[600],
                    ),
              ),
              PopupMenuButton<String>(
                onSelected: (value) {
                  switch (value) {
                    case 'edit':
                      _showEditOrgDialog(org);
                      break;
                    case 'delete':
                      _showDeleteOrgDialog(org);
                      break;
                  }
                },
                itemBuilder: (context) => [
                  const PopupMenuItem(
                    value: 'edit',
                    child: Row(
                      children: [
                        Icon(Icons.edit, size: 20),
                        SizedBox(width: 8),
                        SelectableText('编辑'),
                      ],
                    ),
                  ),
                  const PopupMenuItem(
                    value: 'delete',
                    child: Row(
                      children: [
                        Icon(Icons.delete, size: 20),
                        SizedBox(width: 8),
                        SelectableText('删除'),
                      ],
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
        if (children.isNotEmpty)
          Column(
            children: children
                .map((child) => _buildOrgTreeNode(child, level + 1))
                .toList(),
          ),
      ],
    );
  }

  Widget _buildMobileList(List<Map<String, dynamic>> orgs) {
    return ListView.builder(
      padding: const EdgeInsets.symmetric(horizontal: 16),
      itemCount: orgs.length,
      itemBuilder: (context, index) {
        final org = orgs[index];
        return _buildOrgCard(org);
      },
    );
  }

  Widget _buildOrgCard(Map<String, dynamic> org) {
    return AdaptiveCard(
      child: Row(
        children: [
          const Icon(Icons.account_balance, color: Colors.blue),
          const SizedBox(width: 12),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                SelectableText(
                  org['name'],
                  style: Theme.of(context).textTheme.titleMedium?.copyWith(
                        fontWeight: FontWeight.bold,
                      ),
                ),
                SelectableText(
                  '编码: ${org['code']}',
                  style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                        color: Colors.grey[600],
                      ),
                ),
              ],
            ),
          ),
          PopupMenuButton<String>(
            onSelected: (value) {
              switch (value) {
                case 'edit':
                  _showEditOrgDialog(org);
                  break;
                case 'delete':
                  _showDeleteOrgDialog(org);
                  break;
              }
            },
            itemBuilder: (context) => [
              const PopupMenuItem(
                value: 'edit',
                child: Row(
                  children: [
                    Icon(Icons.edit, size: 20),
                    SizedBox(width: 8),
                    SelectableText('编辑'),
                  ],
                ),
              ),
              const PopupMenuItem(
                value: 'delete',
                child: Row(
                  children: [
                    Icon(Icons.delete, size: 20),
                    SizedBox(width: 8),
                    SelectableText('删除'),
                  ],
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  void _showCreateOrgDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const SelectableText('创建组织'),
        content: _buildOrgForm(),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const SelectableText('取消'),
          ),
          ElevatedButton(
            onPressed: _handleCreateOrg,
            child: const SelectableText('创建'),
          ),
        ],
      ),
    );
  }

  void _showEditOrgDialog(Map<String, dynamic> org) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const SelectableText('编辑组织'),
        content: _buildOrgForm(org: org),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const SelectableText('取消'),
          ),
          ElevatedButton(
            onPressed: _handleUpdateOrg,
            child: const SelectableText('保存'),
          ),
        ],
      ),
    );
  }

  void _showDeleteOrgDialog(Map<String, dynamic> org) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const SelectableText('确认删除'),
        content: SelectableText('确定要删除组织 "${org['name']}" 吗？此操作不可撤销。'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const SelectableText('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              Navigator.of(context).pop();
              _handleDeleteOrg(org);
            },
            style: ElevatedButton.styleFrom(backgroundColor: Colors.red),
            child: const SelectableText('删除'),
          ),
        ],
      ),
    );
  }

  Widget _buildOrgForm({Map<String, dynamic>? org}) {
    return Form(
      key: _formKey,
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          AdaptiveTextField(
            labelText: '组织名称',
            prefixIcon: Icons.account_balance,
            initialValue: org?['name'] ?? '',
            validator: (value) {
              if (value == null || value.isEmpty) {
                return '请输入组织名称';
              }
              return null;
            },
          ),
          const SizedBox(height: 16),
          AdaptiveTextField(
            labelText: '组织编码',
            prefixIcon: Icons.code,
            initialValue: org?['code'] ?? '',
            validator: (value) {
              if (value == null || value.isEmpty) {
                return '请输入组织编码';
              }
              if (value.length < 2) {
                return '组织编码长度不能少于2位';
              }
              return null;
            },
          ),
          const SizedBox(height: 16),
          // 父级组织选择
          TextFormField(
            initialValue: _selectedParentOrg,
            decoration: const InputDecoration(
              labelText: '上级组织',
              border: OutlineInputBorder(),
            ),
            readOnly: true,
            onTap: () => _showParentOrgSelector(context),
          ),
          const SizedBox(height: 16),
          DropdownButtonFormField<String>(
            initialValue: _selectedOrgType,
            decoration: const InputDecoration(
              labelText: '组织类型',
              border: OutlineInputBorder(),
            ),
            items: const [
              DropdownMenuItem(
                value: 'COMPANY',
                child: SelectableText('公司'),
              ),
              DropdownMenuItem(
                value: 'DEPARTMENT',
                child: SelectableText('部门'),
              ),
              DropdownMenuItem(
                value: 'TEAM',
                child: SelectableText('团队'),
              ),
            ],
            onChanged: (value) {
              setState(() {
                _selectedOrgType = value!;
              });
            },
          ),
          const SizedBox(height: 16),
          TextFormField(
            initialValue: _selectedStatus,
            decoration: const InputDecoration(
              labelText: '状态',
              border: OutlineInputBorder(),
            ),
            readOnly: true,
            onTap: () => _showStatusSelector(context),
          ),
        ],
      ),
    );
  }

  Widget _buildParentOrgDropdown(dynamic selectedParentId) {
    // 模拟组织数据用于下拉选择
    final orgs = [
      {'id': 1, 'name': '技术部'},
      {'id': 2, 'name': '产品部'},
      {'id': 3, 'name': '测试部'},
      {'id': 4, 'name': '运维部'},
      {'id': 5, 'name': '设计部'},
    ];

    return DropdownButtonFormField<dynamic>(
      initialValue: selectedParentId,
      decoration: const InputDecoration(
        labelText: '父级组织',
        prefixIcon: Icon(Icons.folder),
      ),
      items: [
        const DropdownMenuItem(
          value: null,
          child: SelectableText('顶级组织'),
        ),
        ...orgs.map((org) => DropdownMenuItem(
              value: org['id'],
              child: SelectableText(org['name'] as String),
            )),
      ],
      onChanged: (value) {
        // 处理父级组织选择变化
      },
    );
  }

  void _handleCreateOrg() {
    if (_formKey.currentState!.validate()) {
      // TODO: 实现创建组织逻辑
      Navigator.of(context).pop();
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: SelectableText('组织创建成功')),
      );
    }
  }

  void _handleUpdateOrg() {
    if (_formKey.currentState!.validate()) {
      // TODO: 实现更新组织逻辑
      Navigator.of(context).pop();
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: SelectableText('组织信息更新成功')),
      );
    }
  }

  void _handleDeleteOrg(Map<String, dynamic> org) {
    // TODO: 实现删除组织逻辑
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: SelectableText('组织"${org['name']}"删除成功')),
    );
  }

  void _showParentOrgSelector(BuildContext context) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const SelectableText('选择上级组织'),
        content: _buildParentOrgDropdown(_selectedParentOrg),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const SelectableText('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              Navigator.of(context).pop();
              // TODO: 处理上级组织选择
            },
            child: const SelectableText('确定'),
          ),
        ],
      ),
    );
  }

  void _showStatusSelector(BuildContext context) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const SelectableText('选择状态'),
        content: DropdownButtonFormField<String>(
          initialValue: _selectedStatus,
          decoration: const InputDecoration(
            labelText: '状态',
            border: OutlineInputBorder(),
          ),
          items: const [
            DropdownMenuItem(
              value: 'ACTIVE',
              child: SelectableText('活跃'),
            ),
            DropdownMenuItem(
              value: 'INACTIVE',
              child: SelectableText('停用'),
            ),
          ],
          onChanged: (value) {
            setState(() {
              _selectedStatus = value!;
            });
          },
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const SelectableText('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              Navigator.of(context).pop();
              // TODO: 处理状态选择
            },
            child: const SelectableText('确定'),
          ),
        ],
      ),
    );
  }
}
